<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/12/2
  Time: 11:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<%--<form action="fileUpload" method="post" enctype="multipart/form-data">--%>
<%--    <p>选择文件：<input type="file" name="fileName"></p>--%>
<%--    <input type="submit" value="提交">--%>
<%--</form>--%>
<div>
    <a href="javascript:void(0)" id="selectPhoto" onclick="uploadPhoto()">选择图片</a>

    <input type="file" id="photoFile" style="display: none;" onchange="upload()">

    <img id="preview_photo" src="" width="200px" height="200px" hidden>

    <input type="text" name="photoPath" id="productImg" hidden>
</div>

<script>
    function uploadPhoto() {
        $("#photoFile").click();
    }
    function upload() {
        var aaa = new FormData();
        aaa.append('photo', document.getElementById('photoFile').files[0]);
        $.ajax({
            url:"${pageContext.request.contextPath}/uploadPhoto",
            type:"post",
            data: aaa,
            contentType: false,
            processData: false,
            success: function(data) {
                if (data.type == "success") {
                    $("#preview_photo").attr("src", data.filepath+data.filename);
                    $("#productImg").val(data.filename);
                    $("#preview_photo").show();
                } else {
                    alert(data.msg);
                }
            },
            error:function(data) {
                alert("上传失败")
            }
        });
    }
</script>
</body>
</html>